﻿using KAKA.Domain;
using KAKA.Repository;
using Morus;
using Morus.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace KAKA.Infrastructure
{
    public class DefaultSetting : IBootstrapperTask
    {
        private List<Setting> _settings = new List<Setting>();

        public DefaultSetting()
        {
            _settings.Add(new Setting(Setting.NAME_VERIFICATION_CODE_DURATION, 1800));
            _settings.Add(new Setting(Setting.NAME_ONE_HOUR_ALLOWED_TEXT_MESSAGE_COUNT, 3));
            _settings.Add(new Setting(Setting.NAME_ONE_DAY_ALLOWED_TEXT_MESSAGE_COUNT, 10));
            _settings.Add(new Setting(Setting.NAME_SITE_TITLE, "真爱一生"));
            _settings.Add(new Setting(Setting.NAME_META_KEY, "真爱一生"));
            _settings.Add(new Setting(Setting.NAME_META_DESCRIPTION, "真爱一生"));
            _settings.Add(new Setting(Setting.NAME_EMAIL_ADDRESS, "noreply@zhenai521.com"));
            _settings.Add(new Setting(Setting.NAME_ROOT_URL, "http://localhost:2760"));
        }

        public void Execute()
        {
            using (var uow = UnitOfWork.Begin())
            {
                var settingRepository = IoC.Resolve<ISettingRepository>("database");
                var settingInitialized = settingRepository.GetByName(Setting.NAME_SETTING_INITIALIZED);
                if (settingInitialized == null || Convert.ToBoolean(settingInitialized.Value) == false)
                {
                    foreach (var item in _settings)
                    {
                        var setting = settingRepository.GetByName(item.Name);
                        if (setting == null)
                        {
                            settingRepository.Add(new Setting()
                            {
                                Id = Guid.NewGuid(),
                                Name = item.Name,
                                Value = item.Value,
                            });
                        }
                        else
                        {
                            setting.Value = item.Value;
                        }
                    }

                    if (settingInitialized == null)
                    {
                        settingInitialized = new Setting()
                        {
                            Id = Guid.NewGuid(),
                            Name = Setting.NAME_SETTING_INITIALIZED,
                            Value = true.ToString()
                        };
                        settingRepository.Add(settingInitialized);
                    }
                    else
                    {
                        settingInitialized.Value = true.ToString();
                    }
                }

                uow.Commit();
            }
        }
    }
}